package com.example.demo1.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisStandaloneConfiguration;
import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import redis.clients.jedis.JedisPoolConfig;

@Configuration
public class RedisSingletonConfig {

    @Value("${single.spring.redis.host}")
    private String host;
    @Value("${single.spring.redis.database}")
    private Integer database;
    @Value("${single.spring.redis.jedis.pool.max-active}")
    private Integer maxTotal;
    @Value("${single.spring.redis.jedis.pool.max-idle}")
    private Integer maxIdle;
    @Value("${single.spring.redis.jedis.pool.max-wait}")
    private Long maxWait;
    @Value("${single.spring.redis.jedis.pool.min-idle}")
    private Integer minIdle;

    @Bean(name = "singletonRedisTemplate")
    public RedisTemplate myRedisTemplate() {
        RedisTemplate template = new RedisTemplate();
        template.setConnectionFactory(jedisConnectionFactory());
        setSerializer(template);
        template.afterPropertiesSet();
        return template;
    }
    public JedisConnectionFactory jedisConnectionFactory() {
        JedisConnectionFactory jedisConnectionFactory = new JedisConnectionFactory();
        RedisStandaloneConfiguration standaloneConfiguration = jedisConnectionFactory.getStandaloneConfiguration();
        standaloneConfiguration.setHostName(host);
        standaloneConfiguration.setDatabase(database);
        jedisConnectionFactory.setPoolConfig(jedisPoolConfig());
        return jedisConnectionFactory;
    }
    public JedisPoolConfig jedisPoolConfig() {
        JedisPoolConfig config = new JedisPoolConfig();
        config.setMaxTotal(maxTotal);
        config.setMaxIdle(maxIdle);
        config.setMinIdle(minIdle);
        config.setMaxWaitMillis(maxWait);
        return config;
    }

    /**
     * 设置RedisTemplate的序列化方式
     *
     * @param redisTemplate
     */
    public void setSerializer(RedisTemplate redisTemplate) {
        StringRedisSerializer stringRedisSerializer = new StringRedisSerializer();
        //设置键（key）的序列化方式
        redisTemplate.setKeySerializer(stringRedisSerializer);
        //设置值（value）的序列化方式
        redisTemplate.setValueSerializer(stringRedisSerializer);
        //设置值（hashkey）的序列化方式
        redisTemplate.setHashKeySerializer(stringRedisSerializer);
        //设置值（hashvalue）的序列化方式
        redisTemplate.setHashValueSerializer(stringRedisSerializer);
        redisTemplate.afterPropertiesSet();
    }


}
